package com.eventlogger.event;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.eventlogger.model.CategoryEvent;
import com.eventlogger.model.Event;
import com.eventlogger.model.EventInstance;
import com.eventlogger.model.PMF;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gson.Gson;
import com.google.gwt.http.client.Request;


public class UserEvent extends HttpServlet{
	private static final Logger log = Logger.getLogger(UserEvent.class.getName());

	
	public void doGet(HttpServletRequest req,HttpServletResponse resp) throws IOException
	{
	String requestUri=req.getRequestURI();
	   log.info("requestUri is :" + requestUri);
	   resp.setContentType("text/xml");
	   String response="<root><node label=\"all\" isBranch=\"true\"/></root>";
	   UserService userService=UserServiceFactory.getUserService();
		  User user=getUser();
		  log.info("here");
		   if (user!=null)
		   {
	   
	   if (requestUri.equals("/event/getUserProfileXML/"))
	   {
		   
			   log.info(user.getNickname() + userService.createLogoutURL(req.getRequestURI()));
//			   response="<a href="+userService.createLogoutURL(req.getRequestURI())+">logout</a>";
//			   resp.setContentType("text/html");
			   response="<main><user name=\""+user.getNickname()+"\"  logoutUrl=\""+
			   userService.createLogoutURL(req.getRequestURI())+"\"/>"+"</main>";
			   resp.setContentType("text/xml");
			   
		   }
		   
		   
	   
	   if (requestUri.indexOf("/event/getUserEvents")>-1)
	   {
		   resp.setContentType("text/xml");
		   //log.info(req.getParameter("format"));
		   response=getUserEvents(req.getParameter("format"));
		   
	   }
	   if (requestUri.equals("/event/getUserEventsPhone/"))
	   {
		  response=getUserEventsPhone();
		  resp.setContentType("text/html");
		   
	   }
	  if (requestUri.equals("/event/deleteEventsXML/"))
	  {
		  response=deleteEvent(req,resp);
		  resp.setContentType("text/xml");
	  }
	   
	   if (requestUri.equals("/event/getEventInstances/"))
	   {
		  
		  response=getEventInstances(req);
		  resp.setContentType("text/html");
		   
	   }
	   
	   if (requestUri.equals("/event/userEventListDb/"))
	   {
		   resp.sendRedirect("/userEventListDb.jsp");
	   }
	  
	   log.info(response);
	    
		resp.getWriter().println(response);
		   }
		   else
		   {
			   resp.sendRedirect(userService.createLoginURL(req.getRequestURI()));
		   }
	}
	
	public String getUserEventsPhone() throws IOException
	{
		StringBuffer HTML=new StringBuffer();
	//	HTML.append("" +
			//	"<html xmlns=\\\"http://www.w3.org/1999/xhtml\\\"><head><title>Events</title><meta name=\\\"viewport\""+ 
			//"content=\"width=320; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;\"/><link rel=\"stylesheet\""+ 
			//"media=\"screen\" type=\"text/css\" href=\"/iui/iuix.css\"/></head><body><div class=\"toolbar\">"+
   //     "<h1 id=\"pageTitle\">Events</h1><a class=\"button blueButton\" type=\"cancel\" href=\"{{logoutUrl}}\">Logout</a>" +
        //"<a id=\"backButton\" class=\"button\" href=\"#\"></a></div>" +
     //   "<ul id=\"home\" title=\"Events\" selected=\"true\">");

		PersistenceManager pm = PMF.get().getPersistenceManager();
	     
	     
	     ArrayList<String> eventNames = new ArrayList<String>();

		Query query=pm.newQuery(Event.class,"Email=='"+getUser().getEmail()+"'");
		try
		{
			List<Event> results=(List<Event>) query.execute();
			if (results.iterator().hasNext())
			{
				for (Event e:results)
				{
				 eventNames.add(e.getEventname());
				 log.info(e.getEventname()+" == "+e.getPublished().toString());
				 
				}
				Set set = new HashSet(eventNames);
				ArrayList b = new ArrayList(set);
				
				 for (Object name:b)
                 {
                		//HTML.append("<li><a href=\"/sendSingleEvent\">"+name+"</li>");
					 HTML.append(name+",");
					
                 }
			}
			else
			{
				
			}
			
		}
		finally
		{
			query.closeAll();
			pm.close();
		}
		   
		
	//	HTML.append("</ul><div>" );
				//"</body></html>");
	//	log.info(HTML.toString());
		
		  
		   return HTML.toString().substring(0, HTML.length()-1);
	}
	public String getUserEvents(String format) throws IOException
	{
		PersistenceManager pm = PMF.get().getPersistenceManager();
	     StringBuffer responseString=new StringBuffer();
	     
	     //ArrayList<String> eventNames = new ArrayList<String>();

		Query query=pm.newQuery(Event.class,"Email=='"+getUser().getEmail()+"'");
		List<Event> results=(List<Event>) query.execute();
		 ArrayList<String> eventNames = new ArrayList<String>();
		if (format.equals("json"))
		{
			Gson gson = new Gson();
		    
		     CategoryEvent ce=new CategoryEvent();
		 	for (Event e:results)
			{
			  eventNames.add(e.getEventname());
			}	 
		 	ce.setName("all");
		 	ce.setEvents((List)eventNames);
		 	
		     responseString.append(gson.toJson(ce));
		}
		else
		{
		try
		{
			responseString.append("<root><node label=\"all\">");
			
			log.info("the number of events are :"+results.size());
			if (results.iterator().hasNext())
			{
				for (Event e:results)
				{
		//			responseString.append("<node label=\""+e.getEventname()+"\"/>"); 
				 eventNames.add(e.getEventname());
				 }
				Set set = new HashSet(eventNames);
				ArrayList b = new ArrayList(set);

                 for (Object name:b)
               {
				responseString.append("<node label=\""+name+"\"/>"); 
//                		responseString.append("<Event>"+name+"</Event>");    	 
                 }
			}
			else
			{
				responseString.append("No Event");
			}
		}
		finally
		{
			query.closeAll();
			pm.close();
		}
		responseString.append("</node></root>");
		}

		return responseString.toString();
		
	}
	
	public User getUser()
	{
		 UserService userService=UserServiceFactory.getUserService();
			User user=userService.getCurrentUser();
			return user;
	}
	
	public void doPost(HttpServletRequest req,HttpServletResponse resp) throws IOException
	{
		String postUri=req.getRequestURI();
		
		   log.info("postUri is :" + postUri);
		   if (postUri.equals("/event/submitEventXML/"))
		   {
			   submitEvent(req,resp);
		   }
		   if (postUri.equals("/event/storeEventInstance/"))
		   {
			  storeEventInstance(req, resp);
			  resp.sendRedirect("/userEventListDb.jsp");
			   
		   }
	
	}
	public void submitEvent(HttpServletRequest req,HttpServletResponse resp) throws IOException
	{
	
		String eventName=req.getParameter("eventname");
		String[] propertynames=req.getParameterValues("propertyname");
		String[] propertytypes=req.getParameterValues("propertytypes");
		Boolean storeFailed=false;
		log.info("names= "+propertynames.length);
		
		
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Event[] events=new Event[propertynames.length];
		for (int i=0;i<propertynames.length;i++)
		{
			events[i]=new Event("all",getUser(),getUser().getEmail(),eventName,propertynames[i],"string",new Date(),new Date());

		}
		
		try
		{
			pm.makePersistentAll(events);
		}
		catch(Exception e)
		{
			log.warning(e.getStackTrace()+"\n"+ e.getMessage());
			storeFailed=true;
			//log.log("Error", e.getMessage());
		}
		finally
		{
			pm.close();
		}
		resp.setContentType("text/xml");
		
		if (storeFailed)
		{
		resp.getWriter().println("<Response>Failed</Response>");
		}
		else
		{
			resp.getWriter().println("<Response>Success</Response>");
		}
	

	}
	
	public void storeEventInstance(HttpServletRequest req,HttpServletResponse resp) throws IOException
	{
		String eventname=req.getParameter("eventName");
		String eventtype=req.getParameter("eventType");
		String value=req.getParameter("value");
		PersistenceManager pm = PMF.get().getPersistenceManager();
		String publishedDate=req.getParameter("eventTimestamp");
		DateFormat df = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss");
        log.info(publishedDate);
       log.info(eventname+" "+ eventtype);
		try
	
		{
			EventInstance ei=new EventInstance(eventname,eventtype,getUser().getEmail(),value,df.parse(publishedDate),df.parse(publishedDate));
			
			pm.makePersistent(ei);
		}
		catch(Exception e)
		{
			log.warning(e.getStackTrace()+"\n"+ e.getMessage());
			//log.log("Error", e.getMessage());
		}
		finally
		{
			pm.close();
		}
	}
	
	public String getEventInstances(HttpServletRequest req) throws IOException
	{
		String eventName=req.getParameter("eventName");
		PersistenceManager pm = PMF.get().getPersistenceManager();
		StringBuffer responseString=new StringBuffer();
		
		responseString.append("<head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\" />" +
				"<title>Event Instances</title><link href=\"/css/resultstable.css\" rel=\"stylesheet\" " +
				"type=\"text/css\" /></head>");
		
		responseString.append("<body><table id=\"mytable\" cellspacing=\"0\"><caption>Event Instances </caption><tr><th scope=\"col\" abbr=\"Configurations\"" +
				">Event Name</th><th scope=\"col\" abbr=\"Dual 1.8\">Occurence</th></tr>");
		
		Query query=null;
	    if (eventName!=null)
	    {
		query=pm.newQuery(EventInstance.class,"useremail=='"+getUser().getEmail()+"' && eventname=='"+eventName+"'");
	    }
	    else
	    {
	    	 query=pm.newQuery(EventInstance.class,"useremail=='"+getUser().getEmail()+"'");
	    	 query.setOrdering("published desc");
	    }
		{
			List<EventInstance> results=(List<EventInstance>) query.execute();
			try
			{
			if (results.iterator().hasNext())
			{
				for (EventInstance e:results)
		 		{
					responseString.append(" <tr><th scope=\"row\" abbr=\"Model\" class=\"spec\">"+e.getEventname()+"</th><td>"+e.getPublished().toString()+"</td></tr>");
					}
			}
			else
			{
				responseString.append("No EventInstance");
			}
		}
		finally
		{
			query.closeAll();
			pm.close();
		}
		responseString.append("</table></body></html>");
		return responseString.toString();
	}
	}
	
    public void getEventAttributes(HttpServletRequest req,HttpServletResponse resp) throws IOException
    {
    	String eventName=req.getParameter("eventName");
    	StringBuffer responseString=new StringBuffer();
    	PersistenceManager pm = PMF.get().getPersistenceManager();
    	
    	Query query=pm.newQuery(Event.class,"Email=='"+getUser().getEmail()+"' " +
				"&& eventname=='"+eventName+"'");
    	
    	 
    	 try
    	 {
    		 List<Event> eventList=(List<Event>) query.execute();
    		 if (eventList.iterator().hasNext())
    			{
    				for (Event e:eventList)
    		 		{
    				  responseString.append("<attribute> <name>"+e.getPropertyname()+"</name><type>"+
    						  e.getPropertytype()+"</type></attribute>");
    		 		}
    			}
    	 }
    	 catch(Exception e)
    	 {
    		 log.warning(e.getStackTrace()+"\n"+ e.getMessage());
    		 
    	 }
    	
    	
    }
	public String deleteEvent(HttpServletRequest req,HttpServletResponse resp) throws IOException
	{
		String eventName=req.getParameter("eventName");
		log.info(eventName);
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query query=null;
		query=pm.newQuery(EventInstance.class,"useremail=='"+getUser().getEmail()+"' " +
				"&& eventname=='"+eventName+"'");
		Boolean deleteFailed=false;
	    List<EventInstance> eventInstances=(List<EventInstance>) query.execute();
		try
		{
		if (eventInstances.iterator().hasNext())
		{
			for (EventInstance e:eventInstances)
	 		{
			  pm.deletePersistent(e);
	 		}
		}
		}
		
		catch(Exception e)
		{
			deleteFailed=true;
			log.warning(e.getStackTrace()+"\n"+ e.getMessage());
		}
			//log.log("Error", e.getMessage());
		
		if (!deleteFailed)
		{
		query=pm.newQuery(Event.class,"Email=='"+getUser().getEmail()+"' " +
				"&& eventname=='"+eventName+"'");
	  
		List<Event> results=(List<Event>) query.execute();
			try
			{
			if (results.iterator().hasNext())
			{
				for (Event e:results)
		 		{
				  pm.deletePersistent(e);
		 		}
			}
			}
			catch(Exception e)
			{
				deleteFailed=true;
				log.warning(e.getStackTrace()+"\n"+ e.getMessage());
				//log.log("Error", e.getMessage());
			}
			finally
			{
				pm.close();
			}
		}
		
		if (deleteFailed)
		{
		return "<Response>Failed</Response>";
		}
		else
		{
			return "<Response>Success</Response>";
		}
		 
	}
}
